package com.dzy.kjadmin.components.dydatasource;

import com.google.common.collect.Maps;
import com.xiaoleilu.hutool.util.StrUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 多数据源注册中心
 * Created by dzy20 on 2017-07-07.
 */
@Configuration
public class DynamicDataSourceRegister {

    @Bean
    public DynamicDataSource dataSource(Environment env) {
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        Map<Object, Object> targetDataSources = Maps.newHashMap();
        targetDataSources.put("dataSource", DruidBuildDataSourceExt.create().build(env, "spring.datasource."));//增加默认数据源
        targetDataSources.putAll(initCustomDataSources(env));//增加其余的数据源
        dynamicDataSource.setTargetDataSources(targetDataSources);
        dynamicDataSource.setDefaultTargetDataSource(targetDataSources.get("dataSource"));
        DynamicDataSourceContextHolder.dataSourceIds.addAll(targetDataSources.keySet());
        return dynamicDataSource;
    }

    /**
     * 注册多数据源
     *
     * @param env env
     * @return 多数据源map集合
     */
    private Map<String, DataSource> initCustomDataSources(Environment env) {
        Map<String, DataSource> customDataSources = new HashMap<String, DataSource>();
        String perfixStr = "spring.datasource.custom.";//多数据源前面配置
        String prefixNames = env.getProperty(perfixStr + "names");//多数据源的名称配置，英文逗号分隔
        if(StrUtil.isEmpty(prefixNames)) {
            return customDataSources;
        }
        for (String dsPrefix : StrUtil.split(prefixNames, ",")) {// 多个数据源
            customDataSources.put(dsPrefix, DruidBuildDataSourceExt.create().build(env, perfixStr + dsPrefix + "."));
        }
        return customDataSources;
    }
}
